package com.hdl.servlet.user;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import com.hdl.entity.HdlUser;
import com.hdl.service.UserService;
import com.hdl.service.impl.UserServiceImpl;

/**
 * UploadUserInfoServlet
 * @author 白云苍狗
 *
 */
@WebServlet("/uploadUserInfo.let")
public class UploadUserInfoServlet extends HttpServlet{
	
	private UserService service = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		
		//获取参数
		Map<String, String[]> map = req.getParameterMap();
		
		//从session中获取user对象
		HdlUser user = (HdlUser) req.getSession().getAttribute("user");
		
		//新建用户对象
		HdlUser hdlUser = new HdlUser();
		
		//防止时间类型转换出错
		DateConverter dc = new DateConverter();//创建时间类型转换器
		dc.setPattern("yyyy-MM-dd");//设置转换格式
		ConvertUtils.register(dc, java.util.Date.class);
		
		//封装属性
		try {
			BeanUtils.populate(hdlUser, map);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		//赋值非空属性
		hdlUser.setHdlUserId(user.getHdlUserId());
		hdlUser.setHdlUserName(user.getHdlUserName());
		hdlUser.setHdlUserPsd(user.getHdlUserPsd());
		hdlUser.setSysRoleId(user.getSysRoleId());
		hdlUser.setHdlUserLog(user.getHdlUserLog());
		hdlUser.setHdlUserScore(user.getHdlUserScore());
		hdlUser.setHdlUserStatus(user.getHdlUserStatus());
		//调用用户业务逻辑方法
		service.update(hdlUser);
		user = service.selectById(user.getHdlUserId());
		
		//重新将用户数据存入session中
		req.getSession().setAttribute("user", user);
		
		//转发
		req.getRequestDispatcher("/usercenter/user1.jsp").forward(req, resp);
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
